<template>
  <!-- 搜索工作栏 -->
  <!-- <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择文件类型"
          clearable
          class="!w-240px"
        >
          <el-option label="PDF转Word" :value="2" />
          <el-option label="其他类型" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap> -->

  <!-- 刷新上加个提示，刷新可以shua -->
  <el-button type="primary" @click="getList" style="margin-bottom: 10px">刷新</el-button>
  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="ID" align="center" prop="id" width="80" /> -->
      <el-table-column label="原始文件名" align="center" prop="originFileName" min-width="160px" />
      <el-table-column label="转换后文件名" align="center" prop="fileName" min-width="160px" />
      <el-table-column label="类型" align="center" prop="type" width="120">
        <template #default="scope">
          <el-tag type="success">PDF转Word</el-tag>
          <span style="display: none">{{ scope.row.type }}</span>
          <!-- <el-tag v-if="scope.row.type === 2" type="success">PDF转Word</el-tag>
          <el-tag v-else type="info">其他类型</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center" prop="type" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 1" type="primary">继远</el-tag>
          <el-tag v-else-if="scope.row.type === 2" type="info">埃森哲</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <!-- <el-button link type="primary" @click="handlePreview(scope.row)" v-if="scope.row.path">
            预览
          </el-button> -->
          <el-button link type="success" @click="handleDownload(scope.row)"> 下载 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 预览对话框 -->
  <el-dialog v-model="previewVisible" title="文件预览" width="80%" top="5vh">
    <div v-if="currentFile" class="file-preview">
      <div class="file-info mb-15px">
        <p><strong>文件名:</strong> {{ currentFile.fileName }}</p>
        <p><strong>原始文件名:</strong> {{ currentFile.originFileName }}</p>
        <p><strong>路径:</strong> {{ currentFile.path }}</p>
      </div>
      <div v-if="isWordFile" class="preview-container">
        <el-alert
          title="Word文件需要下载后才能查看完整内容"
          type="info"
          :closable="false"
          class="mb-15px"
        />
        <el-button type="primary" @click="handleDownload(currentFile)">
          <Icon icon="ep:download" class="mr-5px" /> 下载文件
        </el-button>
      </div>
      <div v-else-if="isPdfFile" class="preview-container">
        <el-alert
          title="PDF文件需要下载后才能查看完整内容"
          type="info"
          :closable="false"
          class="mb-15px"
        />
        <el-button type="primary" @click="handleDownload(currentFile)">
          <Icon icon="ep:download" class="mr-5px" /> 下载文件
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ChatMessageApi } from '@/api/ai/chat/message'

import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getAccessToken } from '@/utils/auth'

defineOptions({ name: 'ResumeTransferNotesList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  fileName: undefined,
  type: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

// 预览相关变量
const previewVisible = ref(false)
const currentFile = ref<any>(null)
const isWordFile = ref(false)
const isPdfFile = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      fileName: queryParams.fileName,
      type: queryParams.type,
      createTimeBegin: queryParams.createTime?.[0],
      createTimeEnd: queryParams.createTime?.[1]
    }
    const response = await ChatMessageApi.getTransferPage(params)
    console.log('🚀 ~ getList ~ response:', response)
    list.value = response.list
    total.value = response.total
  } catch (error) {
    console.error('获取列表失败:', error)
    message.error('获取列表失败，请重试')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 预览文件 */
const handlePreview = (row: any) => {
  currentFile.value = row
  isWordFile.value =
    row.fileName?.toLowerCase().endsWith('.docx') || row.fileName?.toLowerCase().endsWith('.doc')
  isPdfFile.value = row.fileName?.toLowerCase().endsWith('.pdf')
  previewVisible.value = true
}

/** 下载文件 */
const handleDownload = async (row: any) => {
  console.log('🚀 ~ handleDownload ~ row:', row)
  const { id, fileName } = row
  try {
    loading.value = true
    // window.open(
    //   `http://localhost:48080/admin-api/ai/chat/resume/transfer/download?id=${id}&token=${getAccessToken()}`,
    //   '_blank'
    // )
    const params = {
      // pageNo: queryParams.pageNo,
      // pageSize: queryParams.pageSize,
      id
    }
    const response = await ChatMessageApi.exportNotesList(params)
    // console.log('🚀 ~ getList ~ response:', response)
    download.word(response, `${fileName}.docx`)
  } catch (error) {
    console.error('下载文件失败:', error)
    message.error('下载文件失败，请重试')
  } finally {
    loading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.file-preview {
  height: 60vh;
  overflow-y: auto;
}

.preview-container {
  display: flex;
  height: 40vh;
  background-color: #f9f9f9;
  border: 1px dashed #ccc;
  border-radius: 4px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
